package com.cskaoyan.order.mq.delay;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.Charset;

/**
 * @author bai
 * @since 2022/08/02 22:56
 */
@Component
public class DelayOrderCancelProducer {
    private DefaultMQProducer producer;
    @PostConstruct
    public void init(){
        producer = new DefaultMQProducer("delay_order_cancel_producer");

        producer.setNamesrvAddr("127.0.0.1:9876");

        try {
            producer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }

    public boolean sendDelayOrderCancelMassage(String orderId){
        // 准备待发送
        Message message = new Message();
        message.setTopic("delay_order_cancel");
        message.setBody(orderId.getBytes(Charset.forName("utf-8")));

        // 设置延迟消息的延迟级别
        message.setDelayTimeLevel(3);

        SendResult sendResult = null;
        try {
           sendResult = producer.send(message);
        } catch (MQClientException e) {
            e.printStackTrace();
        } catch (RemotingException e) {
            e.printStackTrace();
        } catch (MQBrokerException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if(sendResult != null && SendStatus.SEND_OK.equals(sendResult.getSendStatus())){
            // 消息发送成功
            System.out.println("12345=6=========");
            return true;
        }
        // 消息发送失败
        return false;
    }
}
